﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Heaven.Engine.Concurrency
{
    /// <summary>
    /// Class with locking ability
    /// </summary>
    public class ConcurrentObject
    {
        ConcurrentLock locker = new ConcurrentLock();

        /// <summary>
        /// Locks this object
        /// </summary>
        /// <returns>Lock</returns>
        public ConcurrentLock Lock()
        {
            locker.Lock();
            return locker;
        }
    }

    /// <summary>
    /// Represents lock
    /// </summary>
    public class ConcurrentLock : IDisposable
    {
        // Mutex to lock
        Mutex mutex = new Mutex(false);

        /// <summary>
        /// Performs lock
        /// </summary>
        public void Lock()
        {
            if (!mutex.WaitOne(120000, false))
            {
                throw new Exception("Deadlock has been occured in Heaven engine");
            }
        }

        /// <summary>
        /// Performs unlock
        /// </summary>
        public void Dispose()
        {
            mutex.ReleaseMutex();
        }
    }
}
